<template>
  <div class="editDevice" @click="closeAllHistory">
    <el-dialog :visible.sync="centerDialogVisible"
               :close-on-click-modal="clickModalHide"
               :before-close="closeDialog"
                width="645px"
               :title="type=='add'?'新建设备':'修改设备'">
      <el-form label-position="left"   :model="editData" size="mini" status-icon :rules="rules" ref="editData" label-width="100px"
               :inline="true"    class="demo-ruleForm">
        <el-form-item label="资产编码：" class="label-dis">
          <el-input v-model="editData.assetCode" placeholder="提交后不可修改" :disabled="assetCodeDisable"></el-input>
        </el-form-item>
        <el-form-item label="设备名称：" prop="name">
          <el-input v-model="editData.name" ></el-input>
        </el-form-item>
        <el-form-item label="制造商：" prop="producer">
          <el-input  v-model="editData.producer"
                     @keyup.native="selectItem($event)"></el-input>
          <div class="search-list-show" v-show="autoTip.length > 0 && tipShow" id="scrollElement">
            <ul class="choose-history" >
              <li v-for="(item,index) in autoTip"
                  :key="index"
                  :class="{'active':currentIndex == index}"
                  @click="chooseTip(item)">{{item}}</li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label="设备编码：" prop="deviceCode">
          <el-input v-model="editData.deviceCode" :disabled="type == 'edit'" ></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="deviceStatus">
          <el-select v-model="editData.deviceStatus" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in deviceStatusList"
              :key="index"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号：" prop="type">
          <el-input v-model="editData.type" ></el-input>
        </el-form-item>
        <el-form-item label="属性：" prop="attr">
          <el-select v-model="editData.attr" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in attrList"
              :key="index"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量：" prop="deviceCount">
          <el-input v-model="editData.deviceCount" disabled></el-input>
        </el-form-item>

        <el-form-item label="使用部门：" prop="dept">
          <el-select v-model="editData.dept" placeholder="请选择"  @change="changeDept">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id">
              <span style="float: left">{{ item.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptLevel }}级</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科别：" prop="deptLevel" ref="deptLevelForm">
          <el-select v-model="editData.deptLevel" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in deptLevelList"
              :key="index"
              :label="item.deptName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修人：" prop="repairMan" class="label-dis">
          <el-input  v-model.number="editData.repairMan" ></el-input>
        </el-form-item>

        <el-form-item label="投用日期：" prop="userDate">
          <el-date-picker
            :disabled="type == 'edit'"
            style="width: 92%"
            v-model="editData.userDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="电话：" prop="phone" class="label-dis">
          <el-input  v-model="editData.phone" ></el-input>
        </el-form-item>

        <el-form-item label="价值：" class="label-dis">
          <el-input  v-model="editData.price" ></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center;margin-top: 15px">
        <el-button type="primary" @click="submitForm('editData')">提交</el-button>
        <el-button @click="resetForm('editData')" style="margin-bottom: 20px">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'editDevice',
    props: ['dataDetail','type'],
    data() {
      let phoneValidator = (rule, value, callback) => {
        let mobile = /^1[3|5|8]\d{9}$/ , phone = /^0\d{2,3}-?\d{7,8}$/;
        if (value &&!mobile.test(value) && !phone.test(value)) {
          return callback(new Error('请输入正确的电话号码'));
        } else {
          callback();
        }
      };
      let priceValidator = (rule, value, callback) => {
        if (value && /[^\d.]/g.test(value)) {
          return callback(new Error('请输入正确的价值'));
        } else {
          callback();
        }
      };

      return {
        centerDialogVisible: false,
        clickModalHide: false,
        editData: {
          id:"",
          assetCode:"",
          name:"",
          type:"",
          deviceCount:"1",
          producer:"",
          price:"",
          userDate:"",
          attr:"",
          dept:"",
          deptLevel:"",
        },
        checkProp:["name","type","producer","userDate","attr","dept","deviceCode","deviceStatus"],
        produceNameList:[],
        autoTip:[],
        tipShow:false,
        clickTip:false,

        deviceStatusList:[{name:"在用",value:"0"},{name:"备用",value:"1"}],
        attrList:[{name:"一般"},{name:"重点"},{name:"关键"},{name:"特种"}],

        deptList:[],
        deptLevelList:[],

        assetCodeDisable:false,

        currentIndex:-1,

        isEnter:false,

        rules: {
          phone: [
            {validator: phoneValidator, trigger: 'blur'}
          ],
          price: [
            {validator: priceValidator, trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请输入型号规格',trigger: 'blur'}
          ],
          deviceCode: [
            {required: true, message: '请输入设备编码',trigger: 'blur'}
          ],
          deviceStatus: [
            {required: true, message: '请选择状态',trigger: 'change'}
          ],
          deviceCount: [
            {required: true, message: '',trigger: 'change'}
          ],
          name: [
            {required: true, message: '请输入设备名称',trigger: 'blur'}
          ],
          attr: [
            {required: true, message: '请选择属性',trigger: 'change'}
          ],
          dept: [
            {required: true, message: '请选择部门',trigger: 'change'}
          ],
          deptLevel: [
            {required: true, message: '请选择科别',trigger: 'change'}
          ],
          userDate: [
            {required: true, message: '请选择日期',trigger: 'blur'}
          ],
          producer: [
            {required: true, message: '请输入制造商',trigger: 'blur'}
          ]
        },
        count: 0,
      }
    },
    mounted() {
      let self = this;
      this.getProduceName();
      this.getDeptList();
      self.$eventBus.$on("closeDeviceHistory",function () {
        self.tipShow = false;
        self.currentIndex = -1
      });
    },

    computed:{
      producer(){
        return this.editData.producer;
      },
    },

    methods: {

      resetDept(){
        let currentDept = [];
        let deptFlag = false;
        let dept = this.editData.dept;
        for(let item of this.deptList){
          if(item.id == dept){
            deptFlag = true;
            currentDept = dept.children||[];
            break;
          }
        }
        if(deptFlag){
          for(let child of currentDept){
            if(child.id == this.editData.deptLevel){
                return;
            }
          }
          this.editData.deptLevel = "";
        }else{
          this.editData.dept = "";
          this.editData.deptLevel = "";
        }
      },

      closeAllHistory(){
        this.tipShow = false;
        this.currentIndex = -1
      },
      selectItem(event){
        if(this.autoTip.length == 0){
          return;
        }
        if(event.code == "Enter"){
          this.isEnter = true;
          this.editData.producer = this.autoTip[this.currentIndex];
          return;
        }
        let scrollHeight = document.getElementById("scrollElement").scrollHeight;
        let height = document.getElementById("scrollElement").clientHeight;
        let dis = Math.round((scrollHeight - height)/this.autoTip.length);
        if(event.code == "ArrowDown" && this.currentIndex < this.autoTip.length-1){
          this.currentIndex++;
          document.getElementById("scrollElement").scrollTop =document.getElementById("scrollElement").scrollTop + dis;
        }
        if(event.code == "ArrowUp" && this.currentIndex > 0){
          document.getElementById("scrollElement").scrollTop =document.getElementById("scrollElement").scrollTop - dis;
          this.currentIndex --;
        }
      },

      getDeptList() {
        let self = this;
        self.$http({
          url: "/autoMonitor/dept/queryDeptList",
          method: "post",
          params: {convertChild: false}
        }).then(resp => {
          if (resp.success) {
            self.deptList = resp.result;
          }
        });
      },

      changeDept(){
        this.deptLevelList = [];
        this.editData.deptLevel = "";
        for(let dept of this.deptList){
          if(dept.id == this.editData.dept && dept.children){
            this.deptLevelList = dept.children;
          }
        }
      },

      chooseTip(tip){
        this.editData.producer = tip;
        this.tipShow = false;
        this.clickTip = true;
      },

      isChinese(str){
        let reg = /[\u4e00-\u9fa5]/gm;
        return reg.test(str)
      },


      operateDevice() {
        let self = this;
        let deviceCode = self.editData.deviceCode;
        if(deviceCode && self.isChinese(deviceCode.substring(0,1))){
          self.$notify({
            title: '提示',
            message: "设备编码首字母不为中文",
            type: 'error'
          });
           return;
        }
        let url = this.type == 'add'?'/autoMonitor/manage/addDevice':'/autoMonitor/manage/editDevice';
        if (this.count == 0) {
          self.$http({
            url: url,
            method: "post",
            data: JSON.stringify(self.editData),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.resetForm('editData');
              self.$eventBus.$emit("updateDevice",self.type);
              self.$notify({
                title: '提示',
                message: self.type == 'add'?"添加成功！":"修改成功",
                type: 'success'
              });
              return
            }else{
              self.$notify({
                title: '提示',
                message:resp.message ,
                type: 'error'
              });
            }
            this.count--;
          });
          this.count++;
        }
      },

      //关闭弹窗
      closeDialog() {
        this.$refs['editData'].clearValidate();
        this.$refs['editData'].resetFields();
        this.centerDialogVisible = false;
      },

      submitForm(formName) {
        let self = this;
        this.$refs[formName].validate((valid) => {
          if(self.deptLevelList.length == 0){
            self.$refs['deptLevelForm'].clearValidate()
          }
          if (self.autoValidator() || valid) {
            self.operateDevice();
          } else {
            return false;
          }
        });
      },

      autoValidator(){
        for(let prop of this.checkProp){
          if(!this.editData[prop]){
            return false;
          }
        }
        return true;
      },


      resetForm(formName) {
        this.$refs[formName].clearValidate();
        this.closeDialog();
      },

      getProduceName(){
        let self = this;
        self.$http({
          url: "/autoMonitor/gz/queryProducerName",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.produceNameList = resp.result;
          }
        });
      }
    },
    watch: {
      dataDetail(val) {
        let self = this;
        this.count = 0;
        this.deptLevelList = [];
        this.centerDialogVisible = true;
        this.assetCodeDisable = false;
        for (let key in this.editData) {
          if (!val.hasOwnProperty(key)) {
            val[key] = "";
          }
        }
        this.editData = val;
        delete this.editData.createTime;
        if(this.editData.deptLevel){
            for(let dept of this.deptList){
              if(dept.id == this.editData.dept && dept.children){
                this.deptLevelList = dept.children;
              }
            }
        }
        if(this.type == 'edit' && this.editData.assetCode){
          this.assetCodeDisable = true;
        }
        this.resetDept();
        self.$nextTick(()=>{
          self.tipShow = false;
        });
      },

      producer(val){
        this.currentIndex = -1;
        let autoNames = [];
        if(this.isEnter){
          this.isEnter = false;
          this.tipShow = false;
          return;
        }
        for(let name of this.produceNameList){
          if(name.indexOf(val) > -1 && val){
            autoNames.push(name);
          }
        }
        if(!this.clickTip){
          this.tipShow = true;
        }
        this.clickTip = false;
        this.autoTip = autoNames;
      }
    }
  }
</script>
<style>
  .editDevice .el-form-item {
    margin-bottom: 15px;
  }

  .editDevice .el-form--inline .el-form-item {
    margin-right: 12px;
  }

  .input_1{
    background: #e0dede;
    border: 1px;
    font-size: 12px;
    font-family: monospace;
  }

  .search-list-show {
    position: absolute;
    top: 28px;
    left: 0;
    background-color: #fff;
    width: calc(100% - 2px);
    border: 1px solid #e4e4e4;
    box-shadow: 0 5px 5px rgba(0, 0, 0, 0.1);
    height: 450%;
    overflow-y:auto;
    z-index: 999 !important;
  }
  .search-list-show ul{
    padding: 0px;
  }

  .search-list-show li {
    list-style-type:none;
    margin: 10px;
    border-bottom: 1px dashed rgba(0, 128, 255, 0.1);
  }

  .search-list-show li:hover,
  .search-list-show li:focus {
    background-color: rgba(0, 128, 255, 0.1);
  }

  .editDevice .el-form-item__label{
    padding: 0px 0px 0px 12px
  }

  .editDevice .el-input--suffix .el-input__inner {
    padding-right: 17px;
  }

  .editDevice .label-dis .el-form-item__label {
    padding: 0px 0px 0px 21px !important;
  }
  .choose-history .active{
    background-color: #6cc6ec3d;
  }
	.select_zl {
		width: calc(100% - 2px);
	}

  .choose-history .active{
    background-color: #6cc6ec3d;
  }

</style>
